package ModelLayer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

public class CustomerRecords {
	
	private ArrayList<Customer> customers;
	private static CustomerRecords instance = null;

	private CustomerRecords() {
		customers = new ArrayList<Customer>();
	}

	public static CustomerRecords getInstance() {
		if (instance == null) {
			instance = new CustomerRecords();
		}
		return instance;
	}

	public Customer getCustomer(int id) throws RealException {
		Customer theCustomer = null;
		boolean found = false;
		Iterator<Customer> it = customers.iterator();
		while (it.hasNext() && !found) {
			Customer customer = it.next();
			if (customer.getId() == id) {
				theCustomer = customer;
				found = true;
			}
		}
		if (!found)
			throw new RealException("Customer was not found");
		return theCustomer;
	}
	
	public ArrayList<Customer> getCustomers() {
		return customers;
	}

	public void removeCustomer(int id) throws RealException {
		Customer customer = getCustomer(id);
		if (customer != null) {
			customers.remove(customer);
		}
	}

	public void updateCustomer(int id, int choise, String newValue)
			throws RealException {
		Customer customer = getCustomer(id);
		if (customer != null) {
			switch (choise) {
			case 1: {
				customer.setName(newValue);
				break;
			}
			case 2: {
				customer.setAddress(newValue);
				break;
			}
			case 3: {
				customer.setPhone(Long.parseLong(newValue));
				break;
			}
			case 4:
				customer.updateGroup(Integer.parseInt(newValue));
				break;
			}
		}
	}

	public void addCustomer(String name, String address, long phone, int group)	throws RealException {
		Customer customer = new Customer(name, address, phone, group);
		customers.add(customer);
	}

	public String printCustomer(int id) throws RealException {
		return getCustomer(id).toString();
	}

	public ArrayList<String> getAllCustomers() {
		ArrayList<String> texts = new ArrayList<String>();
		for (Customer customer : customers) {
			texts.add(customer.toString());
		}
		return texts;
	}
	
	public void checkCustomer(int id) throws RealException {
		boolean found = false;
		Iterator<Customer> it = customers.iterator();
		while (it.hasNext() && !found) {
			Customer customer = it.next();
			if (customer.getId() == id) {
				found = true;
			}
		}
		if (!found)
			throw new RealException("Customer was not found");
	}

	@SuppressWarnings("unchecked")
	public void load(ObjectInputStream obj_in) throws IOException, ClassNotFoundException
	{
		this.customers = (ArrayList<Customer>) obj_in.readObject();
		Customer.setLastId(((Integer)obj_in.readObject()).intValue());
	}
	
	public void save(ObjectOutputStream obj_out) throws IOException
	{		
		obj_out.writeObject(customers);
		obj_out.writeObject(new Integer(Customer.getLastId()));
	}
	
}
